import { v4 as uuid } from 'uuid'
import store from '@/store'
import { StdPage } from '@/utils/parse/page'
import { StdDoc } from '@/utils/parse/doc'
import { getPageByBlockId } from '@/utils/helpers'
import { getContentPageBlockList, rectifyItemLevel, getSiblingPageBlockList, getGroupedBlockList  } from './parse'

export const getLocalPageList = () => {
    const blockList = getContentPageBlockList(true)
    rectifyItemLevel(blockList)
    // 如果是模板 template 或文档 document 页面进入，则正文前后的页面单独处理，最后拼到一起
    const headPageBlockList = getSiblingPageBlockList('head', true)
    const tailPageBlockList = getSiblingPageBlockList('tail', true)
    const groupedBlockList = getGroupedBlockList(blockList)
    const contentPageBlockList = groupedBlockList.map((i) => {
      const page = getPageByBlockId(i?.[0]?.blockId)
      let pageName = "";
      let variableId="";
      const pages = store.getters.contentPages;
      const { pageId, layout: pageLayout } = page?.dataset || {}
      pages.forEach(item=>{
        if(item.pageId === pageId){
          pageName = item.pageName;
          variableId = item.variableId;
        }
      })
      return new StdPage({ pageId, pageLayout, pageType: 'content', blockList: i ,pageName,variableId})
    })
    // 文档的中英文类型透传
    const pageList = [...headPageBlockList, ...contentPageBlockList, ...tailPageBlockList]
    let pageNo = 1
    pageList.forEach((item) => {
      if (!['cover', 'signature', 'revision'].includes(item.pageType)) {
        item.pageNo = pageNo++
      }
    })

    return pageList
}

export const getStrData2Save = () => {
  // 如果是结构化块 block 或个人收藏 collect 页面进入，只有单页的内容
  if (store.getters.editContentType === 'block' || store.getters.editContentType === 'collect') {
    const blockList = getContentPageBlockList(true)
    rectifyItemLevel(blockList)
    const groupId = uuid()
    const data = blockList.map((i) => {
      if (!i.blockType) {
        i.setBlockType(store.getters.editContentType)
      }
      if (!i.groupId) {
        i.setGroupId(groupId)
      }
      return i
    })
    console.debug('---content page data---', data)
    return JSON.stringify(data)
  }

  const pageList = getLocalPageList()
  const docData = new StdDoc({
    pageList,
    languageType: store.getters.languageType
  })
  console.debug('---all pages data---save', docData)
  return JSON.stringify(docData)
}
